package cn.haoran.config;

import cn.haoran.modules.sys.service.SysConfigService;
import com.google.gson.Gson;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Data
/**
 * es全文检索全局配置
 * Create by hanran on 2019/12/21
 */
public class ElasticsearcConfig {
    protected static Logger logger= LoggerFactory.getLogger("Elasticsearc配置");
    @Autowired
    SysConfigService sysConfigService;
    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {
        logger.info("正在获得Elasticsearc配置信息");
        String config = sysConfigService.getValue("ElasticsearcConfig");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(config, map.getClass());
        /* host */
        String host = (String) map.get("host");
        /* 端口 */
        String port = (String) map.get("port");
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, Integer.parseInt(port), "http")
        ));
    }
}
